"""
FileName：allure_util.py
Description：
Author：gaojiahui
Time：2025/8/18 20:11
Website：https://gitee.com/gao-jiahui
"""
import json

import allure

from config.settings import settings


def attach_request_details(method, url, request_kwargs, response):
    """将请求和响应详情附加到Allure报告"""
    # 请求详情
    request_details = f"{method} {url}\n\n"
    request_details += "Headers:\n"
    for key, value in request_kwargs.get('headers', {}).items():
        request_details += f" {key}: {value}\n"

    if 'json' in request_kwargs:
        request_details += "\nRequest Body:\n"
        request_details += json.dumps(request_kwargs['json'], indent=2, ensure_ascii=False)
    elif 'data' in request_kwargs:
        request_details += "\nRequest Data:\n"
        request_details += str(request_kwargs['data'])

    allure.attach(request_details, name="Request Details", attachment_type=allure.attachment_type.TEXT)

    # 响应详情
    response_details = f"Status Code: {response.status_code}\n\n"
    try:
        response_details += json.dumps(response.json(), indent=2, ensure_ascii=False)
    except:
        response_details += response.text

    allure.attach(response_details, name="Response Details", attachment_type=allure.attachment_type.TEXT)

    # 失败时附加截图
    if response.status_code >= 400:
        screenshot_path = settings.SCREENSHOT_DIR / f"error_{method}_{url.split('/')[-1]}.png"
        # 这里实际项目中会使用Selenium截图，但接口测试通常不需要
        # 作为示例，我们创建一个空文件
        with open(screenshot_path, 'w') as f:
            f.write("Error screenshot placeholder")
        allure.attach.file(str(screenshot_path), name="Error Screenshot", attachment_type=allure.attachment_type.PNG)